package csm.sql.pool;

import java.sql.Connection;
import java.sql.SQLException;

import com.microsoft.sqlserver.jdbc.SQLServerConnectionPoolDataSource;

import csm.common.TypeConv;
import csm.sql.ConnectionFactory;
import csm.sql.DBConfig;
import csm.sql.SmartConnection;

/**
 * 
 * @author seungmun
 * @since 2006.1.18.
 * @version
 * @see
 */
public class MSSQLConnectionPool extends ConnectionFactory
{
	SQLServerConnectionPoolDataSource cpds = null;

	@Override
	protected void createConnectionPool() throws SQLException
	{
		if( cpds != null)
		{
			cpds = null;
		}
		
		cpds = new SQLServerConnectionPoolDataSource();
		try
		{
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		}
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}

		DBConfig dbc = DBConfig.getDBConfig(this.connectionName);

		cpds.setApplicationName(dbc.getSettings("connection.application"));
		cpds.setServerName(dbc.getSettings("connection.ip"));
		cpds.setPortNumber(TypeConv.ToInt(dbc.getSettings("connection.port")));
		cpds.setDatabaseName(dbc.getSettings("connection.database"));
		cpds.setUser(dbc.getSettings("connection.user"));
		cpds.setPassword(dbc.getSettings("connection.password"));
	}
	
	@Override
	public Connection getConnection() throws SQLException
	{
		if (cpds == null)
			createConnectionPool();
		
		Connection cn = cpds.getPooledConnection().getConnection();
		return new SmartConnection(cn);
	}

	@Override
	public void closeConnectionPool() throws SQLException
	{
		if (cpds == null) return;
		cpds = null;
	}

	@Override
	public String createMaxQuery(String table, String column, String where)
	{
		StringBuffer sb = new StringBuffer(String.format("SELECT ISNULL(MAX(%s)+1, 1) FROM %s ", column, table));
		if (where != null && where.trim().length() > 0) sb.append("WHERE ").append(where);
		return sb.toString();
	}



}
